package ru.voice2blog.engine;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;


/**
 * User: itimofeev
 * Date: 17.05.11
 * Time: 16:28
 */
public class ConvertListener implements FileListener {

    private static final Logger log = LoggerFactory.getLogger(ConvertListener.class);

    String ffmpegPath = "c:\\programs\\" + "ffmpeg-git-9763420-win32-static" + "\\bin\\ffmpeg.exe";

    /**
     * c:\programs\ffmpeg-git-9763420-win64-static\bin\ffmpeg.exe -i C:\temp\wav\mywav.wav -y -vn -ar 44100 -ac 2 -ab 192 -f mp3 C:\temp\wav\myfile.mp3
     */
    public File processNewFile(File oldFile) {
        log.info("Converting wav file {} to mp3", oldFile.getAbsolutePath());
        File newFile = oldFile;
        try {
            String newFileName = calcTargetFileName(oldFile);
            String params = " -i " + oldFile.getAbsolutePath() + " -y -vn -ar 44100 -ac 2 -ab 192 -f mp3 " + newFileName;
            Runtime runtime = Runtime.getRuntime();
            String cmd = ffmpegPath + " " + params;

            log.info("Executing command: ", cmd);
            Process proc = runtime.exec(cmd);

            StringBuffer err = new StringBuffer();
            Streamer err_stream = new Streamer(proc.getErrorStream(), err);
            StringBuffer out = new StringBuffer();
            Streamer out_stream = new Streamer(proc.getInputStream(), out);

            err_stream.run();
            out_stream.run();

            proc.waitFor();
            newFile = new File(newFileName);
            log.info("Converting complete. ", newFileName);
        } catch (Exception e) {
            log.info("Error on converting file occured" + oldFile.getName(), e);
        }
        return newFile;
    }

    private String calcTargetFileName(File fileName) {
        String absolutePath = fileName.getAbsolutePath();
        absolutePath = absolutePath.substring(0, absolutePath.lastIndexOf("."));
        return absolutePath + ".mp3";
    }

//	public static void main(String[] args) {
//		ConvertListener listener = new ConvertListener();
//		listener.processNewFile(new File("C:\\temp\\wav\\mywav.wav"));
//	}

    class Streamer extends Thread {

        private StringBuffer buffer;
        private InputStream input;

        public Streamer(InputStream in, StringBuffer buffer) {
            input = in;
            this.buffer = buffer;
        }

        public void run() {
            BufferedReader reader = null;
            InputStreamReader sr = null;
            try {

                sr = new InputStreamReader(input);
                reader = new BufferedReader(sr);
                String line;

                while ((line = reader.readLine()) != null) {
                    if (buffer != null) {
                        buffer.append(line).append("\n");
                    }
                    System.out.println(line);
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            } finally {
                try {
                    reader.close();
                } catch (Throwable e) {
                }
                try {
                    sr.close();
                } catch (Throwable e) {
                }
            }

        }

    }
}
